<template>
  <div>
    <div class="loginCont">
      <van-tabs
        :active="active"
        color="#0c8ed0"
        v-if="typeNum === 0"
		@change='vantChange'
      >
        <van-tab title="密码登录">
          <div class="loginCont_div">
            <van-cell-group>
              <van-field
                left-icon="friends-o"
                :value="form.email"
                @change="emailChange"
                placeholder="请输入邮箱号"
                :border="false"
                required
                :error-message="emailError"
              />
            </van-cell-group>
          </div>

          <div class="loginCont_div">
            <van-cell-group>
              <van-field
                left-icon="goods-collect-o"
                :value="form.password"
                password
                placeholder="请输入密码"
                :border="false"
                required
                @change="passwordChange"
                :error-message="passwordError"
              />
            </van-cell-group>
          </div>

          <div class="code">
            <div class="loginCont_div">
              <van-field
                v-model="form.code"
                placeholder="请输入图形验证码"
                :border="false"
                @change="codeChange"
                :error-message="codeError"
              />
            </div>
            <div class="bgcode" @click="refreshCode">{{ identifyCode }}</div>
          </div>
          <div class="password">
            <van-checkbox
              :value="checked"
              shape="square"
              @change="checkedChange"
            >
              记住密码
            </van-checkbox>
            <div @click="forgotPassword">忘记密码</div>
          </div>
          <div class="login">
            <div @click="login">登录</div>
            <div @click="register">注册</div>
          </div>
        </van-tab>
        <van-tab title="短信登录">
          <div class="loginCont_div">
            <van-cell-group>
              <van-field
                label="手机号:"
                :value="form.cell"
                placeholder="请输入手机号"
                :border="false"
                :error-message="cellError"
                @change="cellChange"
              />
            </van-cell-group>
          </div>

          <div class="loginCont_div">
            <van-cell-group>
              <van-field
                :value="form.phoneCode"
                center
                clearable
                placeholder="请输入短信验证码"
                :border="false"
                use-button-slot
                :error-message="phoneCodeError"
                @change="phoneCode"
              >
                <van-button
                  slot="button"
                  size="small"
                  type="info"
                  :disabled="disabled"
                  @click="getCode"
                >
                  {{ codeType }}
                </van-button>
              </van-field>
            </van-cell-group>
          </div>

          <div class="password" style="justify-content: flex-end">
            <div @click="forgotPassword">忘记密码</div>
          </div>
          <div class="login">
            <div @click="codeLogin">登录</div>
            <div @click="register">注册</div>
          </div>
        </van-tab>
      </van-tabs>
      <div v-if="typeNum === 1">
        <div class="loginCon_topB">找回密码</div>
        <div class="center">
          <p class="findpswboy_notic">* 请输入你需要找回登录密码的账户名</p>
          <div class="loginCont_div">
            <van-cell-group>
              <van-field
                left-icon="friends-o"
                :value="form.email"
                @change="emailChange"
                placeholder="请输入邮箱号"
                :border="false"
                required
                :error-message="emailError"
              />
            </van-cell-group>
          </div>
          <div class="code">
            <div class="loginCont_div">
              <van-field
                v-model="form.code"
                placeholder="请输入图形验证码"
                :border="false"
                @change="codeChange"
                :error-message="codeError"
              />
            </div>
            <div class="bgcode" @click="refreshCode">{{ identifyCode }}</div>
          </div>
          <div style="display: flex; justify-content: space-between">
            <p class="tostepone" @click="nextStep">下一步</p>
            <div class="tostepone" v-if="typeNum !== 0" @click="step">
              上一步
            </div>
          </div>
        </div>
      </div>
      <div v-if="typeNum === 2">
        <div class="loginCon_topB">请选择找回方式</div>
        <div class="center">
          <p class="findpswboy_notic mb">* 请选择需要找回登录密码的方式</p>
          <van-radio-group value="1">
            <van-radio name="1">邮箱</van-radio>
          </van-radio-group>
          <div class="loginCont_div">
            <van-cell-group>
              <van-field
                :value="mobilecode"
                center
                clearable
                placeholder="请输入邮箱验证码"
                :border="false"
                use-button-slot
                :error-message="mobilecodeError"
                @change="mobilecodeChange"
              >
                <van-button
                  slot="button"
                  size="small"
                  type="info"
                  :disabled="attcode"
                  @click="getEmailCode"
                >
                  {{ codeType }}
                </van-button>
              </van-field>
            </van-cell-group>
          </div>
          <div style="display: flex; justify-content: space-between">
            <p class="tostepone" @click="tosteptwo">下一步</p>
            <div class="tostepone" v-if="typeNum !== 0" @click="step">
              上一步
            </div>
          </div>
        </div>
      </div>

      <div v-if="typeNum === 3">
        <div class="loginCon_topB">设置新密码</div>
        <div class="center">
          <p class="findpswboy_notic mb"></p>
          <div class="loginCont_div">
            <van-field
              :value="newpsw"
              center
              clearable
              placeholder="请输入新密码"
              :border="false"
              password
              :error-message="newpswError"
              @change="newpswChange"
            >
            </van-field>
          </div>
          <div class="loginCont_div">
            <van-field
              :value="newaginpsw"
              center
              clearable
              password
              placeholder="请再次输入密码"
              :border="false"
              :error-message="newaginpswError"
              @change="newaginpswChange"
            >
            </van-field>
          </div>
          <div style="display: flex; justify-content: space-between">
            <p class="tostepone" @click="submitpsw" style="margin: 40px auto">
              提交
            </p>
            <div class="tostepone" v-if="typeNum !== 0" @click="step">
              上一步
            </div>
          </div>
        </div>
      </div>
    </div>
  
  </div>
</template>
<script>
export default {
  data() {
    // const VALIDATE_PASSWORD = (rule, value, callback) => {
    //   if (util.isNotEmpty(value) && !validate.validatePassword(value)) {
    //     callback(new Error('密码需为6-20位字符'));
    //   } else {
    //     callback();
    //   }
    // };

    return {
      active: 0,
      identifyCodes: "1234567890",
      emailError: "",
      passwordError: "",
      codeError: "",
      identifyCode: "",
      checked: false,
      form: {
        email: "",
        password: "",
        code: "",
        cell: "",
        phoneCode: "",
      },
      cellError: "",
      disabled: false,
      time: "获取验证码",
      close: null,
      phoneCodeError: "",
      typeNum: 0,
      attcode: false,
      oneMobile: "",
      twoshow: false,
      mobilecode: "",
      mobilecodeError: "",
      threeshow: true,
      newpsw: "",
      newaginpsw: "",
    };
  },
  methods: {
	  vantChange(e){
		  this.active = e.detail.index
		  console.log(e,'快快快',this.active)
	  },
    step() {
      this.typeNum -= 1;
    },
    register() {
      this.$uniRouter.push({
        path: "/register",
      });
    },
    forgotPassword() {
      this.typeNum = 1;
    },
    submitpsw() {
      if (this.newpsw == "") {
        wx.showToast({
          title: "请输入密码",
          icon: "none",
        });
      } else if (this.newaginpsw == "") {
        wx.showToast({
          title: "请再次输入密码",
          icon: "none",
        });
      } else if (this.newpsw !== this.newaginpsw) {
        wx.showToast({
          title: "两次密码输入不一致",
          icon: "none",
        });
      } else {
        this.$httphelper
          .post("/api/LmUserApi/RetrievePassword", {
            Sign: "string",
            Email: this.oneMobile,
            Pwd: this.newpsw,
          })
          .then((res) => {
            if (res.data.data == true) {
              wx.showToast({
                title: "修改成功",
              });
              this.typeNum = 0;
            } else {
              wx.showToast({
                title: "修改失败",
              });
            }
          })
          .catch((err) => {
            console.log("请求失败：" + "err");
          });
      }
    },
    newaginpswChange(e) {
      this.newaginpsw =e.detail;
    },
    newpswChange(e) {
      this.newpsw =e.detail;
    },
    mobilecodeChange(e) {
      this.mobilecode =e.detail;
    },
    // 找回密码第二步点击下一步
    tosteptwo() {
      if (this.form.mobilecode == "") {
        this.mobilecodeError = "请输入邮箱验证码";
        return;
      }
      const Mobile = this.oneMobile;
      const VcStr = this.mobilecode;
      //   if (this.oneCellshow) {
      //     if (this.form.cellcode == "") {
      //       this.$message({
      //         message: "请输入手机验证码",
      //         type: "warning",
      //       });
      //     }
      //     this.Mobile = this.oneCell;
      //     this.VcStr = this.form.cellcode;
      //   }
      this.$httphelper
        .post("/api/SmsEmailCodeApi/SmsEmailCodeOk", {
          Mobile: Mobile,
          VcStr: VcStr,
        })
        .then((res) => {
          if (res.data.data == false) {
            wx.showToast({
              title: "请输入正确的验证码",
              icon: "none",
            });
          } else {
            // this.twoshow = !this.twoshow;
            this.threeshow = true;
            this.typeNum = 3;
          }
        })
        .catch((err) => {
          console.log("请求失败：" + "err");
        });
    },
    getEmailCode() {
      if (this.attcode) {
        return;
      }
      this.attcode = true;
      this.$httphelper
        .post("/api/LmUserApi/MailboxExist", {
          MailBox: this.oneMobile,
        })
        .then((res) => {
          if (res.data.data == false) {
            wx.showToast({
              title: "此邮箱不存在",
              icon: "none",
            });
          } else {
            this.$httphelper
              .post("/api/SmsEmailCodeApi/EmailCode", {
                MailBox: this.oneMobile,
              })
              .then((res) => {
                if (res.data.data == true) {
                  this.time = 300;
                  this.close = setInterval(this.gettime, 1000);
                } else {
                  wx.showToast({
                    title: "信息发送失败",
                    icon: "none",
                  });
                }
              })
              .catch((err) => {
                console.log("请求失败：" + "err");
              });
          }
        })
        .catch((err) => {
          console.log("请求失败：" + "err");
        });
    },
    nextStep() {
      let reg =
        /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if (!reg.test(this.form.email)) {
        this.emailError = "请输入有限的邮箱";
        return;
      } else {
        this.emailError = "";
      }
      if (this.form.code != this.identifyCode) {
        this.codeError = "请输入正确的图片验证码";
        this.refreshCode();
        return;
      } else {
        this.codeError = "";
      }
      this.$httphelper
        .post("/api/LmUserApi/GetTheverification", {
          Sign: "string",
          MailBox: this.form.email,
        })
        .then((res) => {
          if (res.data.data.IsExist == false) {
            wx.showToast({
              title: "此邮箱不存在",
              icon: "none",
            });
          } else {
            this.oneMobile = res.data.data.Email;
            this.twoshow = true;
            this.typeNum = 2;
            // this.oneCell = res.data.data.PhoneNumber;
            // this.oneshow = !this.oneshow;
            // this.twoshow = !this.twoshow;
          }
        })
        .catch((err) => {
          console.log("请求失败：" + "err");
        });
    },
    codeLogin() {
      if (this.form.cell == "") {
        this.cellError = "请输入手机号";
      } else if (this.form.phoneCode == "") {
        this.cellError = "";
        this.phoneCodeError = "请输入验证码";
      } else {
        this.phoneCodeError = "";
        this.$httphelper
          .post("/api/SmsEmailCodeApi/SmsEmailCodeOk", {
            Mobile: this.form.cell,
            VcStr: this.form.phoneCode,
          })
          .then((res) => {
            if (res.data.data == true) {
              this.$httphelper
                .post("/api/LmUserApi/GetPhoneAuthorInfo", {
                  PhoneNumber: this.form.cell,
                })
                .then((res) => {
                  if (res.data.msg == "Success") {
                    this.$localStorage.setItem(
                      "AuthorId",
                      res.data.data.OpenId
                    );
                    this.$localStorage.setItem(
                      "IsMember",
                      res.data.data.IsMember
                    );
                    this.$localStorage.setItem("xuemi", res.data.data.Money);
                    this.$localStorage.setItem(
                      "EndMemberDate",
                      res.data.data.EndMemberDate
                    );
                    this.$localStorage.setItem(
                      "IsEmailVerify",
                      res.data.data.IsEmailVerify
                    );
                    this.$localStorage.setItem("Mobile", res.data.data.Mobile);

                    this.$localStorage.setItem(
                      "userName",
                      res.data.data.Emailaccounts
                    );
                    uni.showToast({
                      title: "登录成功",
                    });
                    if (this.$localStorage.getItem("path") == "register") {
                      // this.$uniRouter.push({
                      //   path: "/index",
                      // });
					  uni.switchTab({
					  	url:'/pages/index/index'
					  })
                    } else {
                      uni.navigateBack({
                        delta: 1,
                      });
                    }
                  } else {
                    uni.showToast({
                      title: "登录失败",
                      icon: "none",
                    });
                  }
                })
                .catch((err) => {
                  console.log("请求失败：" + "err");
                });
            } else {
              wx.showToast({
                title: "验证码错误",
                icon: "none",
              });
            }
          })
          .catch((err) => {
            console.log("请求失败：" + "err");
          });
      }
    },

    // 手机号获取验证码
    getCode() {
      // 加密完成
      var reg_tel =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

      if (this.form.cell == "" || !reg_tel.test(this.form.cell)) {
        this.cellError = "请输入有效的手机号";
      } else {
        if (this.disabled) return;
        this.disabled = true;
        this.cellError = "";
        this.$httphelper
          .post("/api/LmUserApi/PhoneNumberExist", {
            Mobile: this.form.cell,
          })
          .then((res) => {
            if (res.data.data == false) {
              wx.showToast({
                title: "该手机号不存在",
                icon: "none",
              });
              this.disabled = false;
            } else {
              this.$httphelper
                .post("/api/SmsEmailCodeApi/GetSmsCode", {
                  Mobile: this.form.cell,
                })
                .then((res) => {
                  if (res.data.data == true) {
                    this.time = 60;
                    this.close = setInterval(this.gettime, 1000);
                  } else {
                    wx.showToast({
                      title: "发送失败",
                      icon: "none",
                    });
                  }
                })
                .catch((err) => {
                  console.log("请求失败：" + "err");
                });
            }
          })
          .catch((err) => {
            console.log("请求失败：" + "err");
          });
      }
    },
    gettime() {
      if (this.time == 0) {
        this.disabled = false;
        clearInterval(this.close);
        this.time = "获取验证码";
      } else {
        this.time--;
      }
    },
    checkedChange(e) {
      this.checked =e.detail;
    },
    phoneCode(e) {
      this.form.phoneCode =e.detail;
    },
    cellChange(e) {
		console.log(e,'订单')
      this.form.cell =e.detail;
    },
    codeChange(e) {
		console.log(e,'Ll')
      this.form.code =e.detail;
    },
    passwordChange(e) {
      this.form.password =e.detail;
    },
    emailChange(e) {
      this.form.email =e.detail;
    },
    login() {
      console.log(this.checked);
      let reg =
        /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if (!reg.test(this.form.email)) {
        this.emailError = "请输入有限的邮箱";
        return;
      } else {
        this.emailError = "";
      }
      if (!this.form.password) {
        return (this.passwordError = "请输入有效的密码");
      } else {
        this.passwordError = "";
      }
      if (this.form.code != this.identifyCode) {
        this.codeError = "请输入正确的图片验证码";
        this.refreshCode();
        return;
      } else {
        this.codeError = "";
      }
      if (this.checked) {
        this.$localStorage.setItem("email", this.form.email);
        this.$localStorage.setItem("password", this.form.password);
      } else { 
        wx.removeStorageSync("email");
        wx.removeStorageSync("password");
      }
      this.$httphelper
        .post(
          "/api/LmUserApi/GetLmUserLogin",
          // this.$httphelper.post('/api/LmUserApi/GetLmUserLogin',
          {
            Emailaccounts: this.form.email,
            Pwd: this.form.password,
          }
        )
        .then((res) => {
          if (res.data.data.State == "1") {
            // this.$localStorage.setItem('userId',res.data.data.Author.)
            this.$localStorage.setItem("AuthorId", res.data.data.Author.OpenId);
            this.$localStorage.setItem(
              "IsMember",
              res.data.data.Author.IsMember
            );
            this.$localStorage.setItem("xuemi", res.data.data.Author.Money);
            this.$localStorage.setItem(
              "EndMemberDate",
              res.data.data.Author.EndMemberDate
            );
            this.$localStorage.setItem(
              "IsEmailVerify",
              res.data.data.Author.IsEmailVerify
            );
            this.$localStorage.setItem("Mobile", res.data.data.Author.Mobile);
            this.$localStorage.setItem("userName", this.form.email);
            this.$localStorage.setItem("psw", this.form.password);
            uni.showToast({
              title: "登录成功",
            });
            if (
              this.$localStorage.getItem("path") == "register" &&
              !this.$localStorage.getItem("pathsign")
            ) {
              this.$uniRouter.push({
                path: "/index",
              });
            } else if (this.$localStorage.getItem("pathsign") == 111) {
              this.$uniRouter.push({
                path: "/streamingdetail",
                query: {
                  OpCourseId: "411243CAED5391EC",
                  type: "2",
                  Hftype: "1",
                  coursetype: "2",
                  contNav: "2",
                },
              });
            } else {
              wx.navigateBack({
                delta: 1,
              });
            }
          } else if (res.data.data.State == "2") {
            wx.showToast({
              title: "用户不存在,请先注册",
              icon: "none",
            });
          } else if (res.data.data.State == "3") {
            wx.showToast({
              title: "用户密码错误",
              icon: "none",
            });

            this.refreshCode();
            this.form.code = "";
          }
        })
        .catch((err) => {
          console.log("请求失败：" + "err");
        });
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
    },
    //验证码
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
  },
  created() {
    this.form.email = this.$localStorage.getItem("email");
    this.form.password = this.$localStorage.getItem("password");
    this.makeCode(this.identifyCodes, 4);
  },
  computed: {
    codeType() {
      return this.time === "获取验证码" ? this.time : this.time + "s";
    },
  },
};
</script>
<style scoped lang='less'>
.loginCont {
  width: 83% !important;
  margin: 60rpx auto 0;
  position: relative !important;
}
.loginCont_div {
  margin-top: 40rpx;
  padding: 1px;
  border: 1px solid #cbcbcb;
  margin-bottom: 34rpx;
  border-radius: 10rpx;
  position: relative;
}
.code {
  display: flex;
  justify-content: space-between;
  div {
    margin: 0;
    display: flex;
    align-items: center;
  }
  /deep/ .van-cell {
    padding: 0 30rpx;
  }
}

.bgcode {
  display: flex;
  justify-content: center;
  width: 184rpx;
  height:70rpx;
  background: url("https://uniappfile.bosihw.cn/Res/BosihuiwenRes/yyqklm/images/codebg.png");
  letter-spacing: 12rpx;
  font-style: italic;
  line-height: 70rpx;
  text-align: center;
  font-style: 36rpx;
  font-weight: 500;
  color: #3d3c3c;
  border: 1px solid #cbcbcb;
}
.password {
  margin-top: 60rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  div {
    color: #9b9b9b;
    font-size: 28rpx;
  }
}
.login {
  margin-top:60rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  div {
    flex: 1;
    height: 70rpx;
    border-radius: 10rpx;
    text-align: center;
    line-height: 70rpx;
    font-size: 32rpx;
  }
  div:first-of-type {
    margin-right: 40rpx;
    background: #0c8ed0;
    color: #fff;
  }
  div:last-of-type {
    color: #898989;
    border: 1px solid #cbcbcb;
    font-size: 36rpx;
  }
}
.loginCon_topB {
  width: 100%;
  height: 132rpx;
  border-bottom: 1px solid #dfdfdf;
  text-align: center;
  list-style: none;
  width: 100%;
  height: 80rpx;
  color: #0c8ed0;
  font-size: 36rpx;
  text-align: center;
  line-height: 60rpx;
  margin-top: 52rpx;
  font-weight: bold;
  cursor: pointer;
}
.center {
  margin-top: 46rpx;
}
.findpswboy_notic {
  color: #ff7301;
  font-size: 30rpx;
  text-align: center;
}
.tostepone {
  width: 100px;
  height: 60rpx;
  background: #0c8ed0;
  color: #fff;
  cursor: pointer;
  line-height: 60rpx;
  text-align: center;
  font-size: 32rpx;
  margin-top: 108rpx;
}
.mb {
  margin-bottom: 60rpx;
}
</style>